package com.android.bonn.fast.net.interceptor;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * User: HuangYunLin(283857754@qq.com)
 * Date: 2016-08-15
 * Time: 09:01
 * FIXME
 */
public class CachingControlInterceptor implements Interceptor {


    public CachingControlInterceptor() {
    }


    //这是设置在多长时间范围内获取缓存里面
    public static final CacheControl FORCE_CACHE1 = new CacheControl.Builder()
            .onlyIfCached()
            .maxStale(7, TimeUnit.SECONDS)//这里是7s，CacheControl.FORCE_CACHE--是int型最大值
            .build();

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        int maxStaleSeconds = request.cacheControl().maxStaleSeconds();

        if (maxStaleSeconds <= 0) {
            return chain.proceed(request);
        } else {
            request = request.newBuilder()
                    .cacheControl(CacheControl.FORCE_CACHE).build();
            Response response = chain.proceed(request);
            response.newBuilder()
                    .removeHeader("Pragma")
                    .header("Cache-Control", CacheControl.FORCE_CACHE.toString())
                    .build();
            return response;
        }

    }
}
